package main

import (
	"fmt"
	"os"
	"flag"
	"sync"
	"strings"
	"runtime"
	"regexp"
	"encoding/csv"

	"github.com/Luxurioust/excelize"
)

var wg sync.WaitGroup

var xlsxFile string
var outDir 	 string

func init()  {
	f := flag.String("file", "", "input file path")
	o := flag.String("out", "", "output dir path")
	flag.Parse()

	xlsxFile = *f
	outDir   = outputDir(*o)

	isDir, err := dirExists(outDir)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	if !isDir {
		err := os.MkdirAll(outDir, 0777)
		if err != nil {
			fmt.Println(err)
			os.Exit(1)
		}
	}
}

func main()  {
	fmt.Println("file:", xlsxFile, "===> outDir:", outDir)

	xlsx, err := excelize.OpenFile(xlsxFile)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	sheets := xlsx.GetSheetMap()

	for _, sheet := range sheets {
		wg.Add(1)
		go readSheet(xlsx, sheet)
	}

	wg.Wait()
	fmt.Println("done")
	os.Exit(0)
}

func readSheet(xlsx *excelize.File, sheetName string)  {
	defer wg.Done()

	sheetAry := strings.Split(sheetName, "=")
	if len(sheetAry) != 2 {
		return
	}

	var data [][]string

	rows := xlsx.GetRows(sheetName)
	for _, row := range rows {
		var cols []string
		var empty bool

		for _, col := range row {
			if col != "" {
				empty = true
			}

			cols = append(cols, col)
		}

		if !empty {
			continue
		}

		data = append(data, cols)
	}

	writeCsv(sheetAry[0], sheetAry[1], data)
}

func writeCsv(sheetName string, fileName string, data [][]string)  {
	f, err := os.Create(outDir + fileName)
	if err != nil {
		return
	}

	defer f.Close()

	//f.WriteString("\xEF\xBB\xBF") // 增加UTF-8 BOM

	w := csv.NewWriter(f)
	w.WriteAll(data)
	w.Flush()

	fmt.Println("build sheet:" + sheetName + " => " + fileName + " \t ok")
}

func outputDir(dir string) string {
	if isWindow() && dir != "" {
		dir = strings.Replace(dir, "/", "\\", -1)
		dir = strings.Trim(dir, "\\")
		rd, _ := regexp.MatchString(`\:\\?`, dir)
		if rd {
			return dir + sysDir()
		} else {
			return workDir() + sysDir() + dir + sysDir()
		}
	} else if isLinux() && dir != "" {
		dir = strings.Replace(dir, "\\", "/", -1)
		dir = strings.TrimRight(dir, "/")
		if dir[0:1] == "/" {
			return dir + sysDir()
		} else {
			return workDir() + sysDir() + dir + sysDir()
		}
	}

	return workDir() + sysDir()
}

func isWindow() bool {
	return runtime.GOOS == "windows"
}

func isLinux() bool {
	return runtime.GOOS == "linux"
}

func sysDir() string {
	if isWindow() {
		return "\\"
	} else if isLinux() {
		return "/"
	}
	return "/"
}

func workDir() string {
	dir, _ := os.Getwd()
	return dir
}

func dirExists(dir string) (bool, error) {
	_, err := os.Stat(dir)
	if err == nil {
		return true, nil
	}

	if os.IsNotExist(err) {
		return false, nil
	}

	return false, err
}